package cn.jinjimi.domain.data.imp;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.FinishRegisterEvent;
import cn.jinjimi.app.controller.event.GroupEvent;
import cn.jinjimi.app.controller.event.HonorDelEvent;
import cn.jinjimi.app.controller.event.HonorListEvent;
import cn.jinjimi.app.controller.event.InfoUpdateEvent;
import cn.jinjimi.app.controller.event.OpenSiteEvent;
import cn.jinjimi.app.controller.event.PerfectDetailEvent;
import cn.jinjimi.app.controller.event.SiteInfoEvent;
import cn.jinjimi.app.controller.event.SiteStatusEvent;
import cn.jinjimi.app.controller.event.ThemeActivateEvent;
import cn.jinjimi.app.controller.event.ThemeCurrentEvent;
import cn.jinjimi.app.controller.event.ThemePreViewEvent;
import cn.jinjimi.app.controller.event.ThemeStandEvent;
import cn.jinjimi.app.controller.event.UserProfitEvent;
import cn.jinjimi.app.entity.Company;
import cn.jinjimi.app.entity.CompanyType;
import cn.jinjimi.app.entity.Group;
import cn.jinjimi.app.entity.HonorBean;
import cn.jinjimi.app.entity.SiteInfo;
import cn.jinjimi.app.entity.StandTheme;
import cn.jinjimi.app.entity.ThemePreview;
import cn.jinjimi.app.entity.UserProfiles;
import cn.jinjimi.app.entity.UserProfit;
import cn.jinjimi.base.util.LogUtil;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.domain.data.Store;
import cn.jinjimi.domain.data.dto.ProfileDTO;
import cn.jinjimi.domain.data.dto.SiteStatusDTO;
import cn.jinjimi.domain.data.dto.UserProfitDTO;
import cn.jinjimi.domain.data.net.API;
import cn.jinjimi.domain.data.net.UserService;
import cn.jinjimi.domain.store.UserStore;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by zhenhua on 16/7/7.
 */
public class UserStoreImp extends Store implements UserStore {

    @Override
    public void save(UserProfiles profiles) {

    }

    @Override
    public UserProfiles create(String phone, String pwd, String name, String unionId, String openId, String companyName, String companyId) throws IOException {

        Map<String, String> params = new HashMap<>();

        params.put("agent.phone", phone);
        params.put("agent.password", pwd);
        params.put("agent.real_name", name);

        if (StringUtils.isNotEmpty(unionId))
            params.put("agent.union_id", unionId);

        if (StringUtils.isNotEmpty(openId))
            params.put("agent.open_id", openId);

        if (StringUtils.isNotEmpty(companyName))
            params.put("agent.company_name", companyName);

        if (StringUtils.isNotEmpty(companyId))
            params.put("agent.company_id", companyId);

        API.create(UserService.class).register(params).enqueue(new Callback<ProfileDTO>() {
            @Override
            public void onResponse(Call<ProfileDTO> call, Response<ProfileDTO> response) {
                if (response.isSuccessful()) {
                    ProfileDTO dto = response.body();
                    if (dto != null) {

                        Headers headers = response.headers();
                        String token = headers.get(API.JJM_TOKEN_KEY);
                        AccountManager.getInstance().updateAccount(AccountManager.NameKey.TOKEN, token);
                        API.changeToken(token);

                        success(FinishRegisterEvent.class, dto);
                        return;
                    }
                }
                fail(FinishRegisterEvent.class, 0, "");
            }

            @Override
            public void onFailure(Call<ProfileDTO> call, Throwable t) {
                fail(FinishRegisterEvent.class, 0, "");
            }
        });

        return null;
    }

    @Override
    public void fetchProfile(String ssoid) {

    }

    @Override
    public void updateProfile(long ssoid, JSONObject item) {

    }

    @Override
    public UserProfiles getProfile(long ssoid) {
        return null;
    }


    @Override
    public boolean updateProfile(Map<String, String> properties) throws IOException {

        JSONObject data = new JSONObject();
        JSONObject dto = new JSONObject();
        try {
            for (String key : properties.keySet()) {
                data.put(key, properties.get(key));
            }
            dto.put("agent", data);
        } catch (JSONException e) {
            LogUtil.print(e);
            return false;
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), dto.toString());

        Response<ResponseBody> response =
                API.create(UserService.class).updateProfile(requestBody).execute();

        return response.isSuccessful();
    }

    @Override
    public boolean updateProfile(JSONObject jsonObject) throws IOException {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString());

        Response<ResponseBody> response =
                API.create(UserService.class).updateProfile(requestBody).execute();

        return response.isSuccessful();
    }

    @Override
    public UserProfiles setRealName(String name) throws IOException {
        ProfileDTO dto = parseDataAndDispatchEvents(
                API.create(UserService.class).setRealName(name).execute(),
                new PerfectDetailEvent()
        );
        return dto == null ? null : dto.getProfile();
    }

    @Override
    public SiteStatusDTO getAgentSiteStatus(final int type) throws IOException {
        String ssoid = AccountManager.getInstance().getAccount().ssoid;
        final SiteStatusEvent event = new SiteStatusEvent();
        API.create(UserService.class).getAgentSiteStatus(ssoid).enqueue(new Callback<SiteStatusDTO>() {
            @Override
            public void onResponse(Call<SiteStatusDTO> call, Response<SiteStatusDTO> response) {

                if (response.isSuccessful()) {
                    SiteStatusDTO dto = response.body();
                    if (dto != null) {
                        event.state = DataEvent.SUCC;
                        event.data = dto;
                        event.type = type;
                        dispatch(event);
                        return;
                    }
                }
                event.state = DataEvent.FAIL;
                event.msg = response.message();
                event.error = response.code();
                event.type = type;
                dispatch(event);
            }

            @Override
            public void onFailure(Call<SiteStatusDTO> call, Throwable t) {
                event.state = DataEvent.FAIL;
                event.msg = "网络错误";
                event.error = 0;
                event.type = type;
                dispatch(event);
            }
        });

        return null;
    }

    @Override
    public SiteInfo getSiteInfo() throws IOException {
        return parseDataAndDispatchEvents(
                API.create(UserService.class).getSiteInfo().execute(),
                new SiteInfoEvent()
        );
    }

    @Override
    public UserProfit getProfit() throws IOException {
        UserProfitDTO dto = parseDataAndDispatchEvents(
                API.create(UserService.class).getProfit().execute(),
                new UserProfitEvent()
        );

        return dto == null ? null : dto.data;
    }

    @Override
    public boolean setSiteTheme(String id) throws IOException {
        ResponseBody body = parseDataAndDispatchEvents(API.create(UserService.class).setSiteTheme(id).execute(),
                new ThemeActivateEvent());
        return body != null;
    }


    @Override
    public StandTheme.Theme getCurrentSiteTheme() throws IOException {
        StandTheme dto = parseDataAndDispatchEvents(
                API.create(UserService.class).getCurrentThemeInfo().execute(),
                new ThemeCurrentEvent()
        );
        return dto == null ? null : dto.getTheme();
    }

    @Override
    public ThemePreview getThemePreview(String name) throws IOException {
        return parseDataAndDispatchEvents(
                API.create(UserService.class).getSiteThemePreviews(name).execute(),
                new ThemePreViewEvent()
        );
    }

    @Override
    public List<StandTheme.Theme> getThemes() throws IOException {
        StandTheme dto = parseDataAndDispatchEvents(
                API.create(UserService.class).getThemes().execute(),
                new ThemeStandEvent()
        );
        return dto == null ? null : dto.getThemes();
    }

    @Override
    public boolean activateSite() throws IOException {
        ResponseBody body = parseDataAndDispatchEvents(
                API.create(UserService.class).activateSite().execute(),
                new OpenSiteEvent()
        );
        return body != null;
    }


    @Override
    public List<CompanyType> getCompanyTypes() throws IOException {
        Group group = parseDataAndDispatchEvents(
                API.create(UserService.class).getCompanyType().execute(),
                new GroupEvent()
        );
        return group == null ? null : group.getCompanyTypes();
    }


    @Override
    public List<Company> getCompanies(String type) throws IOException {
        Group group = parseDataAndDispatchEvents(
                API.create(UserService.class).getCompany(type).execute(),
                new GroupEvent()
        );
        return group == null ? null : group.getCompanies();
    }


    @Override
    public boolean deleteHonor(String id) throws IOException {
        ResponseBody body = parseDataAndDispatchEvents(
                API.create(UserService.class).deleteHonor(id).execute(),
                new HonorDelEvent()
        );
        return body != null;
    }

    @Override
    public List<HonorBean> getHonors() throws IOException {
        HonorBean dto = parseDataAndDispatchEvents(
                API.create(UserService.class).getHonors().execute(),
                new HonorListEvent()
        );
        return dto == null ? null : dto.getUser_honors();
    }

    @Override
    public UserProfiles getProfile() throws IOException {
        API.create(UserService.class).getProfile().enqueue(new Callback<ProfileDTO>() {
            @Override
            public void onResponse(Call<ProfileDTO> call, Response<ProfileDTO> response) {
                if (response.isSuccessful()) {
                    ProfileDTO dto = response.body();
                    if (dto != null) {
                        AccountManager.getInstance().setLocalProfilesForLoadProfiles(dto.getProfile());
                        success(InfoUpdateEvent.class, null);
                    }
                }
            }

            @Override
            public void onFailure(Call<ProfileDTO> call, Throwable t) {

            }
        });


        return null;
    }
}
